package com.polaris.live.utils

import android.app.Activity
import android.content.Context
import androidx.fragment.app.Fragment
import com.blankj.utilcode.util.ActivityUtils
import com.gyf.immersionbar.SupportRequestBarManagerFragment
import com.polaris.live.cache.CommonCache
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.mvvm.activity.BaseVmActivity
import com.polaris.live.common.util.LogExt
import com.polaris.live.constant.TrackEventConst
import com.polaris.live.constant.TrackEventConst.CALLBALANCE_FRAGMENT
import com.polaris.live.constant.TrackEventConst.CALLVIDEO_FRAGMENT
import com.polaris.live.constant.TrackEventConst.LIVESPECTATOR_FRAGMENT
import com.polaris.live.constant.TrackEventConst.MESSAGESINGLE_FRAGMENT
import com.polaris.live.constant.TrackEventConst.PAYCALLEND_ACTIVITY
import com.polaris.live.constant.TrackEventConst.TRACK_CLICK
import com.polaris.live.constant.TrackEventConst.USERSPACE_ACTIVITY
import com.polaris.live.dialog_fragment.GiftDialogFragment
import com.polaris.live.manager.TrackPushManager
import com.polaris.live.ui.live.activity.end.call.PayCallEndActivity
import com.polaris.live.ui.live.fragment.CallBalanceFragment
import com.polaris.live.ui.live.fragment.CallVideoFragment
import com.polaris.live.ui.live.fragment.LiveSpectatorFragment
import com.polaris.live.ui.login.LoginActivity
import com.polaris.live.ui.login.PhoneNumberActivity
import com.polaris.live.ui.login.verify.VerifyActivity
import com.polaris.live.ui.main.fragment.HomeRecommendFragment
import com.polaris.live.ui.main.fragment.HotManFragment
import com.polaris.live.ui.main.fragment.HotManNewcomerFragment
import com.polaris.live.ui.main.fragment.HotWomanFragment
import com.polaris.live.ui.main.fragment.HotWomanNewcomerFragment
import com.polaris.live.ui.message.fragment.MessageSingleFragment
import com.polaris.live.ui.recharge.RechargeActivity
import com.polaris.live.ui.user_space.UserSpaceActivity
import com.polaris.live.ui.welcome.WelcomeActivity
import com.polaris.live.utils.fragment.FragmentUtils

/**
 * 埋点帮助
 *
 * @author Created by 半仙 on 2024/1/2/002 16:26
 */
object TrackHelper {

    /**
     * 发布埋点
     *
     * @param page 页面
     * @param event 事件id
     * @param eventType 对象属性   默认给的click  需要什么传什么
     * @param params 参数
     * 如果你传fragment 或者 activity 需要在下面的map里加映射奥
     */
    fun postTrack(
        page: Activity,
        event: String,
        eventType: String = TRACK_CLICK,
        params: Map<String, String> = emptyMap(),
    ) {
        val parameter = getParameter(page)
        if (parameter != null) {
            TrackPushManager.postEvent(parameter.first, event, parameter.second, params, eventType)
        }
    }

    //参数同上  只是这个可以传fragment
    fun postTrack(
        page: Fragment,
        event: String,
        eventType: String = TRACK_CLICK,
        params: Map<String, String> = emptyMap(),
    ) {
        val parameter = getParameter(fragment = page)
        if (parameter != null) {
            TrackPushManager.postEvent(parameter.first, event, parameter.second, params, eventType)
        }
    }

    //如果你不是fragment 也不是 activity 是个奇怪的位置话就传你需要的String吧
    fun postTrack(
        page: String,
        event: String,
        eventType: String = TRACK_CLICK,
        params: Map<String, String> = emptyMap(),
    ) {
        val parameter = getParameter(namePage = page)
        if (parameter != null) {
            TrackPushManager.postEvent(parameter.first, event, parameter.second, params, eventType)
        }
    }

    fun trackActivity(page: Activity, event: String, eventType: String = TRACK_CLICK) {
        val parameter = getParameter(page)
        if (parameter != null) {
            trackGo(parameter.first, event, parameter.second, eventType)
        }
    }

    fun trackFragment(page: Fragment, event: String, eventType: String = TRACK_CLICK) {
        val parameter = getParameter(fragment = page)
        if (parameter != null) {
            trackGo(parameter.first, event, parameter.second, eventType)
        }
    }

    private fun trackGo(page: String, event: String, pageId: String, eventType: String) {
        val ipCountry = CommonCache.getIpCountry()
        val map = if (ipCountry != null) {
            mapOf("ipCountry" to ipCountry)
        } else {
            emptyMap()
        }
        TrackPushManager.postEvent(page, event, pageId, map, eventType)
    }

    fun loginForMap(): Map<String, String> {
        val ipCountry = CommonCache.getIpCountry()
        return if (ipCountry != null) {
            mapOf("ipCountry" to ipCountry)
        } else {
            emptyMap()
        }
    }

    fun rechargeForMap(map: MutableMap<String, String>? = null): MutableMap<String, String> {
        val user = UserManager.getUser()

        val mMap = map ?: mutableMapOf()

        user.device?.ipCountry?.let { ipCountry ->
            mMap["ipCountry"] = ipCountry
        }
        mMap["sex"] = user.sex.toString()

        return mMap
    }

    //映射map找对应的值
    private fun getParameter(
        activity: Activity? = null,
        fragment: Fragment? = null,
        namePage: String? = null,
    ): Pair<String, String>? {
        val pageName = if (activity != null) {
            PAGE_NAMES[activity::class]
        } else if (fragment != null) {
            PAGE_NAMES[fragment::class]
        } else namePage

        if (pageName == null) {
            if (activity != null) {
                LogExt.logE(TrackPushManager.TAG, "page is null ${activity::class.simpleName}")
            } else if (fragment != null) {
                LogExt.logE(TrackPushManager.TAG, "page is null ${fragment::class.simpleName}")
            } else {
                LogExt.logE(TrackPushManager.TAG, "You must give me a page name")
            }
            return null
        }
        val pageId = if (activity != null && activity is BaseVmActivity<*>) {
            activity.getPageId()
        } else {
            CommonUtils.uuid()
        }

        return pageName to pageId
    }

    //充值埋点映射出fragment或者activity
    fun rechargePageMap(context: Context): String {
        //获取fragmentManager
        val fragmentManager = FragmentUtils.getFragmentManager(context)
        //如果等于空代表顶部没有fragment
        if (fragmentManager != null) {
            val fragmentList = fragmentManager.fragments
            //ImmersionBar 会添加一个SupportRequestManagerFragment 这个fragment在app里，所以直接过滤掉 生成一个新的list
            val filteredList = fragmentList.filterNot { it is SupportRequestBarManagerFragment }

            val topFragment = filteredList.lastOrNull()
            topFragment ?: return rechargePageAcMap().pageToString()

            //如果是GiftDialogFragment则不管继续向上获取
            return if (topFragment::class == GiftDialogFragment::class) {
                val toplastFragment = filteredList.getOrNull(filteredList.size - 2)
                //如果GiftDialogFragment上面没有了就找activity
                toplastFragment?.let { com.blankj.utilcode.util.FragmentUtils.getSimpleName(it) }
                    ?: rechargePageAcMap()
            } else {
                com.blankj.utilcode.util.FragmentUtils.getSimpleName(topFragment)
            }.pageToString()
        } else {
            return rechargePageAcMap().pageToString()
        }
    }

    private fun rechargePageAcMap(): String? {
        val topActivity = ActivityUtils.getTopActivity()
        return topActivity?.javaClass?.simpleName
    }

    private val PAGE_NAMES = mapOf(
        WelcomeActivity::class to TrackEventConst.WELCOME_ACTIVITY,
        LoginActivity::class to TrackEventConst.LOGIN_ACTIVITY,
        PhoneNumberActivity::class to TrackEventConst.PHONENUMBER_ACTIVITY,
        VerifyActivity::class to TrackEventConst.VERIFY_ACTIVITY,
        HomeRecommendFragment::class to TrackEventConst.HOME_FRAGMENT,
        HotManFragment::class to TrackEventConst.HOTMAN_FRAGMENT,
        HotManNewcomerFragment::class to TrackEventConst.HOTMANNEWCOMER_FRAGMENT,
        HotWomanFragment::class to TrackEventConst.HOTWOMAN_FRAGMENT,
        HotWomanNewcomerFragment::class to TrackEventConst.HOTWOMANNEWCOMER_FRAGMENT,
        RechargeActivity::class to TrackEventConst.RECHARGE_ACTIVITY
    )

    private fun String?.pageToString(): String {
        if (this == null) return "unknown"
        //映射页面
        return when (this) {
            UserSpaceActivity::class.simpleName -> USERSPACE_ACTIVITY                   //他人空间
            CallVideoFragment::class.simpleName -> CALLVIDEO_FRAGMENT                   //视频通话
            LiveSpectatorFragment::class.simpleName -> LIVESPECTATOR_FRAGMENT           //观众端
            CallBalanceFragment::class.simpleName -> CALLBALANCE_FRAGMENT               //拨打余额不足
            MessageSingleFragment::class.simpleName -> MESSAGESINGLE_FRAGMENT           //私聊页面
            PayCallEndActivity::class.simpleName -> PAYCALLEND_ACTIVITY                 //通话结束页
            else -> "unknown"
        }
    }
}